package com.nut.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nut.course.common.Result;
import com.nut.course.entity.TagUser;
import com.nut.course.mapper.BizTagUserMapper;
import com.nut.course.service.TagUserService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.WxCpTagService;
import me.chanjar.weixin.cp.bean.WxCpTag;
import me.chanjar.weixin.cp.bean.WxCpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;

@Service
@Slf4j
public class TagUserServiceImpl implements TagUserService {

    @Autowired
    private WxCpService wxCpService;

    @Autowired
    private BizTagUserMapper bizTagUserMapper;

    @Override
    public Result<List<TagUser>> getTagsByUserId(String userId) {
        List<TagUser> tagUsers = bizTagUserMapper.selectList(
                new LambdaQueryWrapper<TagUser>().
                        select(TagUser::getTagId, TagUser::getTagName).
                        eq(TagUser::getUserId, userId));
        return Result.ok(tagUsers);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result syncTagData() {

        bizTagUserMapper.delete(new LambdaQueryWrapper<TagUser>().gt(TagUser::getId, 0));

        try {
            WxCpTagService tagService = wxCpService.getTagService();
            List<WxCpTag> wxCpTags = tagService.listAll();

            for (WxCpTag wxCpTag : wxCpTags) {
                String id = wxCpTag.getId();
                String name = wxCpTag.getName();
                List<WxCpUser> wxCpUsers = tagService.listUsersByTagId(id);
                for (WxCpUser wxCpUser : wxCpUsers) {
                    TagUser tagUser = new TagUser();
                    tagUser.setTagId(id);
                    tagUser.setTagName(name);
                    tagUser.setUserId(wxCpUser.getUserId());
                    bizTagUserMapper.insert(tagUser);
                }
            }
        } catch (Throwable t) {
            log.error("syncTagData_error", t);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        return Result.ok();
    }
}
